package com.rainbow.autocode.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rainbow.autocode.dao.SysGeneratorDao;
import com.rainbow.autocode.entity.SqlDmlEntity;
import com.rainbow.autocode.utils.GenUtils;
import freemarker.template.Configuration;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author 付为地
 * @email 1335157415@qq.com
 * @date 2016年12月19日 下午3:33:38
 */
@Service
public class SysGeneratorService {
	@Autowired
	private SysGeneratorDao sysGeneratorDao;

	@Autowired
	Configuration freemaker;

	public List<Map<String, Object>> queryList(Map<String, Object> map) {
		return sysGeneratorDao.queryList(map);
	}

	public int queryTotal(Map<String, Object> map) {
		return sysGeneratorDao.queryTotal(map);
	}

	public Map<String, String> queryTable(String tableName,String schema) {
		return sysGeneratorDao.queryTable(tableName,schema);
	}

	public List<Map<String, String>> queryColumns(String tableName,String schema) {
		return sysGeneratorDao.queryColumns(tableName,schema);
	}

	public byte[] generatorCode(JSONArray tableNames, SqlDmlEntity dmlEntity) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for (int i = 0; i <tableNames.size() ; i++) {
			JSONObject jsonObject=tableNames.getJSONObject(i);
			String tableName=jsonObject.getString("tableName");
			Boolean isFallBack=jsonObject.getBoolean("fallBack");
			//查询表信息
			Map<String, String> table = queryTable(tableName,dmlEntity.getSchema());
			//查询列信息
			List<Map<String, String>> columns = queryColumns(tableName,dmlEntity.getSchema());
			//表指定的类名
			String tableAlias= jsonObject.getString("pojo");
			//第一个表,
			if(i==0){
				//生成代码
				GenUtils.generatorCode(freemaker,table, columns, zip,dmlEntity,true,isFallBack,tableAlias);
			}else{
				//生成代码
				GenUtils.generatorCode(freemaker,table, columns, zip,dmlEntity,false,isFallBack,tableAlias);
			}
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}

}
